package br.sales.view.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;

import br.sales.persistence.DB4OAppSingleton;
import br.sales.view.util.ViewUtil;

import com.db4o.EmbeddedObjectContainer;
import com.db4o.ObjectContainer;

@WebListener(value="appRequestListener")
public class AppRequestListener implements ServletRequestListener{

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		 ObjectContainer session = (ObjectContainer) sre.getServletRequest().getAttribute(ViewUtil.REQUEST_OBJECT_CONTAINER);
		 close(session);
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		EmbeddedObjectContainer rootContainer = DB4OAppSingleton.getMainContainer();
	    ObjectContainer session = rootContainer.ext().openSession();
	    sre.getServletRequest().setAttribute(ViewUtil.REQUEST_OBJECT_CONTAINER, session);
	}
	
	private void close(ObjectContainer session){
		if (session != null){
			session.close();
		}
	}

}
